package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.service.PrizeService;
import cn.com.connext.scrm.service.QrCodeService;
import cn.com.connext.scrm.service.dto.*;
import cn.com.connext.scrm.utils.QRcodeUtils;
import cn.com.connext.scrm.web.rest.vm.*;
import com.codahale.metrics.annotation.Timed;
import com.connext.common.web.rest.BaseResource;
import cn.com.connext.scrm.client.MemberClient;
import cn.com.connext.scrm.domain.master.Activity;
import cn.com.connext.scrm.domain.master.AwardRecord;
import cn.com.connext.scrm.service.ActivityService;
import cn.com.connext.scrm.service.PrizeService;
import cn.com.connext.scrm.service.QrCodeService;
import cn.com.connext.scrm.service.dto.*;
import cn.com.connext.scrm.service.mapper.ActivitiesService;
import cn.com.connext.scrm.utils.QRcodeUtils;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.req.*;
import cn.com.connext.scrm.web.rest.resp.QueryActivitiesResp;
import cn.com.connext.scrm.web.rest.resp.QueryNowAndPostActivitiesResp;
import cn.com.connext.scrm.web.rest.vm.*;
import com.alibaba.fastjson.JSON;
import com.codahale.metrics.annotation.Timed;
import com.connext.common.exception.ServiceException;
import com.connext.common.web.rest.BaseResource;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;


/**
 * Created by cuijian on 2021/05/11.
 */
@RestController
@RequestMapping("/api/HxqrCode")
public class QrCodeResource extends BaseResource {
    private final Logger log = LoggerFactory.getLogger(QrCodeResource.class);
    @Autowired
    private QrCodeService qrcodeService;
    @Autowired
    private PrizeService prizeService;

    public QrCodeResource() throws TimeoutException {
        super("QrCode");
    }



    /**
     * 二维码列表
     * @param vm
     * @return
     */
    @PostMapping("/list")
    @Timed
    @ApiOperation(value = "二维码列表", tags = {"活动配置"}, notes = "二维码列表")
    public JsonResult drawList(@RequestBody QueryQrCodeVM vm) {
        JsonResult result = new JsonResult();

        try {
            Page<QrCodeDTO> page = qrcodeService.queryDrawList(vm);
            result.setData(page);
            result.setState(0);
            result.setMessage("查询成功");
            return result;
        } catch (Exception e) {
            log.error("查询失败:{}", e);
            return null;
        }
    }


    /**
     * 新建
     * @param vm
     * @return
     */
    @PostMapping("/add")
    @Timed
    @ApiOperation(value = "二维码新建", tags = {"活动配置"}, notes = "二维码新建")
    public ResponseEntity addQrcode(@RequestBody QrCodeListVM vm) {
        JsonResult result = new JsonResult();
        try {
            if(qrcodeService.addQrCodeCheck(vm)==false){
                result.setState(-1);
                result.setMessage("已存在,不可重复添加");
            }
            else{
                vm.setCreateTime(new Date());
                QrCodeDTO dto = qrcodeService.add(vm);
                result.setState(0);
                result.setMessage("新建成功");
                result.setData(dto);
            }
            return entityResponse(result);
        } catch (Exception e) {
            log.error("新建失败:{}", e);
            result.setState(1);
            result.setMessage("新建失败");
            return entityResponse(result);
        }
    }
    /**
     * 修改状态
     * @param vm
     * @return
     */
    @PostMapping("/updateStatus")
    @Timed
    @ApiOperation(value = "修改状态", tags = {"活动配置"}, notes = "二维码状态更新")
    public ResponseEntity updateStatus(@RequestBody QrCodeListVM vm) {
        JsonResult result = new JsonResult();
        try {
            //可以加判断不为空的条件
            QrCodeDTO dto = qrcodeService.update(vm);
            result.setState(0);
            result.setMessage("更新成功");
            result.setData(dto);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("更新失败:{}", e);
            result.setState(1);
            result.setMessage("更新失败");
            return entityResponse(result);
        }
    }
    /**
     * 查看二维码
     * @param vm
     * @return
     */
    @PostMapping("/selectByid")
    @Timed
    @ApiOperation(value = "查看", tags = {"活动配置"}, notes = "二维码查看")
    public ResponseEntity selectByid(@RequestBody QrCodeListVM vm) {
        JsonResult result = new JsonResult();
        try {
            //可以加判断不为空的条件
            QrCodeDTO dto = qrcodeService.selectByid(vm);
            result.setState(0);
            result.setMessage("查看成功");
            result.setData(dto);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("查看失败:{}", e);
            result.setState(1);
            result.setMessage("查看失败");
            return entityResponse(result);
        }
    }

    /**
     * 核销
     * @param vm
     * @return
     */
    @PostMapping("/updatePrize")
    @Timed
    @ApiOperation(value = "二维码扫码核销", tags = {"活动配置"}, notes = "二维码扫码核销")
    public ResponseEntity updatePrize(@RequestBody PrizeHxVM vm) {
        JsonResult result = new JsonResult();
        try {

            if(StringUtils.isEmpty(vm.getUnionId()) || StringUtils.isEmpty(String.valueOf(vm.getGoodId()))
                || StringUtils.isEmpty(vm.getBeScanCode()) || StringUtils.isEmpty(String.valueOf(vm.getId()))){
                result.setState(88);
                result.setMessage("参数异常");
            }
            else{
                HxPrizeDTO dto = prizeService.hxPrize(vm);
                result.setState(dto.getHxReturn());
                result.setData(dto);
                switch(dto.getHxReturn()){
                    case 0 :
                        result.setMessage("核销失败");
                        break;
                    case 1 :
                        result.setMessage("核销成功");
                        break;
                    case 5 :
                        result.setMessage("此核销码不存在");
                        break;
                    case 6 :
                        result.setMessage("非本次核销用二维码，核销失败。请联系现场工作人员");
                        break;

                    default :
                        result.setMessage("已核销，不可重复核销");

                }
            }
            return entityResponse(result);
        } catch (Exception e) {
            log.error("核销:{}", e);
            result.setState(-1);
            result.setMessage("核销失败");
            return entityResponse(result);
        }
    }

    @GetMapping(value="/createQrCode")
    public String getQRCode(String qrCodeId) throws IOException {

        return QRcodeUtils.crateQRCode(qrCodeId,200,200);
    }

    /**
     * 根据二维码名称模糊查询二维码
     * @param vm
     * @return
     */
    @PostMapping("/queryQrCodeBySceneName")
    @Timed
    @ApiOperation(value = "查询", tags = {"活动配置"}, notes = "根据二维码名称模糊查询二维码")
    public ResponseEntity queryQrCodeBySceneName(@RequestBody QrCodeListVM vm) {
        JsonResult result = new JsonResult();
        try {
            result.setState(0);
            result.setMessage("根据二维码名称模糊查询二维码成功");
            result.setData(qrcodeService.queryQrCodeBySceneName(vm));
            return entityResponse(result);
        } catch (Exception e) {
            log.error("根据二维码名称模糊查询二维码失败:{}", e);
            result.setState(1);
            result.setMessage("根据二维码名称模糊查询二维码失败");
            return entityResponse(result);
        }
    }
}

